<template>
  <div class="page">
    <div class="drivebox">
      <DriveFactors />
      <div class="panel-footer"></div>
    </div>
    <div class="topInfo">
      <TopInfo :activeYear="activeYear" :yearmeanNpp="yearmeanNpp[i]" />
    </div>
    <div ref="threedmap_ref" class="map"></div>
    <div class="bg1"></div>
    <div class="barbox">
      <countyBarChart />
      <div class="panel-footer"></div>
    </div>

    <div class="panel">
      <h2>NPP区域占比情况</h2>
      <div ref="piechart_ref" class="piechart"></div>
      <div class="panel-footer"></div>
    </div>

    <div class="panel1">
      <h2>变化分析</h2>
      <history />
      <div class="panel-footer"></div>
    </div>
  </div>
</template>

<script>
import YearTrend from "@/components/YearTrend.vue";
import history from "@/components/history.vue";
import countyBarChart from "@/components/countyBarChart.vue";
import DriveFactors from "@/components/DriveFactors.vue";
import TopInfo from "@/components/TopInfo.vue";
import ganjiang from "../../public/static/geojson/npp/赣江.json";
export default {
  name: "Analysis",
  components: {
    Map,
    YearTrend,
    history,
    countyBarChart,
    DriveFactors,
    TopInfo,
  },
  data() {
    return {
      fit: "cover",
      pieChartInstance: null, //
      chartInstance: null,
      activeIndex: "/analyse",
      time: 2000,
      index: 0, //数据索引
      uptrend: "",
      downtrend: "",
      alldata: [],
      activeYear: 2015, //年份换数据
      intervalID: null, //定时器
      yearmeanNpp: [698.667, 691.237, 734.498, 725.422, 706.355, 727.828],
      i: 0,
    };
  },
  async created() {
    await this.sendData()
  },
  mounted() {
    this.init3DChart();
    this.map3DChart();
    this.pieChart();
    this.startInterval();
    //当窗体的尺寸发生改变时，图表大小也随之改变
    window.addEventListener("resize", this.screenAdapter);
  },
  beforeDestroy() {
    this.clearResources();
  },
  methods: {
    //3D柱状图数据
    async getMapChartData() {
      let countyInfo = [];
      const areanpp = (
        await this.axios.get(`/static/geojson/npp/${this.activeYear}.json`)
      ).data.features;
      const county = (await this.axios.get(`/static/geojson/npp/points.json`))
        .data.features;
      county.forEach((e) => {
        let c = {
          NAME: e.properties.NAME,
          coordinates: e.geometry.coordinates,
        };
        countyInfo.push(c);
      });
      countyInfo.forEach((item) => {
        const matchedItem = areanpp.find(
          (a1Item) => a1Item.properties.NAME === item.NAME
        );
        if (matchedItem) {
          item.npp_mean = matchedItem.properties.npp_mean || 500.78;
        }
      });
      return countyInfo;
    },
    init3DChart() {
      this.chartInstance = this.$echarts.init(this.$refs.threedmap_ref);
      this.$echarts.registerMap("ganjiang", ganjiang);
      const option = {
        tooltip: {
          backgroundColor: "rgba(16,12,42,0.9)",
          trigger: "item",
          textStyle: {
            color: "#fff",
          },
          axisPointer: {
            type: "cross",
            axisPointer: {
              type: "cross",
              label: {
                backgroundColor: "#161522",
              },
            },
          },
        },
        geo3D: {
          show: true,
          // 3D地图配置
          map: "ganjiang",
          boxHeight: 50,
          zoom: 1, // 适当放大地图
          bottom: "-5%",
          emphasis: {
            label: {
              show: false,
            },
          },
          itemStyle: {
            color: "#0f2d5d", // 地图底色
            opacity: 0.5,
            borderWidth: 1,
            borderColor: "#1bb4d6",
          },
          viewControl: {
            // 视角控制
            distance: 250, // 观察距离
            rotateSensitivity: 1, // 旋转灵敏度
            zoomSensitivity: 1, // 缩放灵敏度
            alpha: 60, // 水平旋转角度（0-360）
            beta: 10, // 垂直倾斜角度（0-90）
            autoRotate: false, // 自动旋转
          },
          regionHeight: 3, // 地图区域凸起高度
          shading: "lambert",
        },
        series: [
          {
            type: "bar3D", // 3D柱状图系列
            coordinateSystem: "geo3D", // 绑定到geo3D坐标系
            barSize: 4, // 柱体尺寸
            minHeight: 1,
            shading: "lambert", // 材质：realistic|color|lambert
            label: {
              // 标签
              show: true,
              formatter: (params) => {
                return `${params.name}`;
              },
              textStyle: {
                color: "#fff",
              },
            },
            itemStyle: {
              color: "rgb(13, 188, 121)",
            },
            emphasis: {
              // 高亮样式
              itemStyle: {
                color: "#abd9e9",
              },
            },
          },
        ],
      };
      this.chartInstance.setOption(option);
    },
    //3D柱状图
    async map3DChart() {
      const nppdata = await this.getMapChartData();
      const data = nppdata.map((item) => ({
        name: item.NAME,
        value: [
          item.coordinates[0],
          item.coordinates[1],
          typeof item.npp_mean === "number" ? item.npp_mean.toFixed(2) : 562.78,
          15,
        ], // [经度, 纬度, 高度, 柱宽]
        emphasis: {
          label: {
            show: true,
          },
        },
      }));
      const option = {
        tooltip: {
          formatter: (params) => {
            const data = params.value; // [经度, 纬度, 高度, 宽度]
            return `
      <div style="font-weight:bold">${params.name}</div>
      <div>经度：${data[0].toFixed(2)}</div>
      <div>纬度：${data[1].toFixed(2)}</div>
      <div>NPP均值：<span>${data[2]}</span></div>
    `;
          },
        },
        series: [
          {
            data: data,
          },
        ],
      };

      this.chartInstance.setOption(option);
    },
    //饼图
    async pieChart() {
      this.pieChartInstance = this.$echarts.init(this.$refs.piechart_ref);
      const nppdata = await this.getMapChartData();
      let sum = 0;
      nppdata.forEach((e) => {
        if (e.npp_mean) {
          sum += e.npp_mean;
        }
      });

      const data = nppdata.map((item) => ({
        name: item.NAME,
        value:
          typeof item.npp_mean === "number" ? item.npp_mean.toFixed(2) : 562.78, //(item.npp_mean/sum*100).toFixed(2)
      }));
      let rich = {
        white: {
          color: "#ddd",
          align: "center",
          padding: [3, 0],
        },
      };
      let option = {
        tooltip: {
          trigger: "item",
        },
        legend: {
          show: false,
        },
        series: [
          {
            name: "",
            type: "pie",
            radius: ["40%", "70%"],
            avoidLabelOverlap: false,
            label: {
              show: true,
              position: "outside",
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 20,
                fontWeight: "bold",
              },
            },
            labelLine: {
              show: true,
            },
            itemStyle: {
              normal: {
                label: {
                  show: true,
                  position: "outside",
                  color: "#ddd",
                  formatter: (params) => {
                    let percent = 0;
                    let total = 0;
                    for (let i = 0; i < data.length; i++) {
                      if (data[i].value) total += Number(data[i].value);
                    }
                    percent = ((params.value / total) * 100).toFixed(2);
                    if (params.name !== "") {
                      return params.name + "\n{white|" + percent + "%}";
                    } else {
                      return "";
                    }
                  },
                  rich: rich,
                },
                labelLine: {
                  length: 10,
                  length2: 30,
                  show: true,
                  color: "#00ffff",
                },
              },
            },
            data: data,
          },
        ],
      };
      this.pieChartInstance.setOption(option);
    },
    //给图表组件发送数据
    async sendData() {
      this.alldata = await this.getMapChartData();
      this.$bus.$emit("chartdata", this.alldata);
    },
    //开启定时器
    startInterval() {
      //如果有定时器开启，就先清除
      if (this.intervalID) {
        clearInterval(this.intervalID);
      }
      this.intervalID = setInterval(() => {
        this.activeYear++;
        this.i++;
        if (this.activeYear > 2020 || this.i > 5) {
          this.activeYear = 2015;
          this.i = 0;
        }
        this.sendData();
        this.map3DChart();
        this.pieChart();
      }, 3000);
    },
    //清理资源
    // 清理资源
    clearResources() {
      clearInterval(this.intervalID);
      this.intervalID = null;

      [this.chartInstance, this.pieChartInstance].forEach((instance) => {
        if (instance) {
          instance.dispose();
          instance = null;
        }
      });
      window.removeEventListener("resize", this.screenAdapter);
    },
    // 窗口调整适配
    screenAdapter() {
      [this.chartInstance, this.pieChartInstance].forEach((instance) => {
        if (instance) {
          instance.resize();
        }
      });
    },
  },
  watch: {},
};
</script>

<style scoped>
.page {
  padding: 10px;
  width: 100%;
  height: 100%;
  font-family: "华文楷体";
  background: url("../../public/static/img/bg1.jpg") no-repeat;
  background-size: cover;
  background-position: 0 90%;
}
.topInfo {
  margin: 0 auto 0;
  width: 38%;
  height: 15%;
  z-index: 2;
}
.drivebox {
  position: absolute;
  top: 10px;
  left: 5px;
  height: 55%;
  width: 27%;
  border: 1px solid rgba(25, 186, 139, 0.17);
  background: rgba(255, 255, 255, 0.04);
  margin-bottom: 0.1875rem;
}
.drivebox::before {
  position: absolute;
  top: 0;
  left: 0;
  content: "";
  width: 10px;
  height: 10px;
  border-top: 2px solid #02a6b5;
  border-left: 2px solid #02a6b5;
}
.drivebox::after {
  position: absolute;
  top: 0;
  right: 0;
  content: "";
  width: 10px;
  height: 10px;
  border-top: 2px solid #02a6b5;
  border-right: 2px solid #02a6b5;
}
.barbox {
  position: absolute;
  bottom: 5px;
  left: 5px;
  height: 40%;
  width: 27%;
  border: 1px solid rgba(25, 186, 139, 0.17);
  background: rgba(255, 255, 255, 0.04);
}
.barChart {
  width: 100%;
  height: 100%;
}
.barbox::before {
  position: absolute;
  top: 0;
  left: 0;
  content: "";
  width: 10px;
  height: 10px;
  border-top: 2px solid #02a6b5;
  border-left: 2px solid #02a6b5;
}
.barbox::after {
  position: absolute;
  top: 0;
  right: 0;
  content: "";
  width: 10px;
  height: 10px;
  border-top: 2px solid #02a6b5;
  border-right: 2px solid #02a6b5;
}
.panel {
  position: absolute;
  bottom: 5px;
  right: 5px;
  height: 50%;
  width: 28%;
  border: 1px solid rgba(25, 186, 139, 0.17);
  background: rgba(255, 255, 255, 0.04);
  padding: 0 0.1875rem 0;
  margin-bottom: 0.1875rem;
}
.panel::before {
  position: absolute;
  top: 0;
  left: 0;
  content: "";
  width: 10px;
  height: 10px;
  border-top: 2px solid #02a6b5;
  border-left: 2px solid #02a6b5;
}
.panel::after {
  position: absolute;
  top: 0;
  right: 0;
  content: "";
  width: 10px;
  height: 10px;
  border-top: 2px solid #02a6b5;
  border-right: 2px solid #02a6b5;
}
.panel-footer {
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
}
.panel-footer::before {
  position: absolute;
  bottom: 0;
  left: 0;
  content: "";
  width: 10px;
  height: 10px;
  border-bottom: 2px solid #02a6b5;
  border-left: 2px solid #02a6b5;
}
.panel-footer::after {
  position: absolute;
  bottom: 0;
  right: 0;
  content: "";
  width: 10px;
  height: 10px;
  border-bottom: 2px solid #02a6b5;
  border-right: 2px solid #02a6b5;
}
h2 {
  height: 30px;
  line-height: 30px;
  text-align: center;
  color: #fff;
  font-size: 18px;
  font-weight: 400;
}
.piechart {
  padding: 4px;
  /* background-color: rgb(16, 12, 42); */
  background-color: rgba(0, 0, 0, 0);
  position: absolute;
  width: 100%;
  height: 100%;
}
.panel1 {
  position: absolute;
  bottom: 52%;
  right: 5px;
  height: 46%;
  width: 28%;
  border: 1px solid rgba(25, 186, 139, 0.17);
  background: rgba(255, 255, 255, 0.04);
  padding: 0 0.1875rem 0;
  margin-bottom: 0.1875rem;
}
.panel1::before {
  position: absolute;
  top: 0;
  left: 0;
  content: "";
  width: 10px;
  height: 10px;
  border-top: 2px solid #02a6b5;
  border-left: 2px solid #02a6b5;
}
.panel1::after {
  position: absolute;
  top: 0;
  right: 0;
  content: "";
  width: 10px;
  height: 10px;
  border-top: 2px solid #02a6b5;
  border-right: 2px solid #02a6b5;
}
.map {
  padding: 5px;
  position: absolute;
  top: 1%;
  left: 21%;
  width: 58%;
  height: 100%;
  overflow: hidden;
  z-index: 2;
}
.map::before {
  content: "";
  position: absolute;
  top: 10%;
  left: 0;
  width: 100%;
  height: 100%;
  background: url("../assets/map.png") no-repeat center;
  background-size: 50% 60%;
  opacity: 0.3; /* 透明度 50% */
  z-index: 0; /* 确保伪元素在内容下方 */
}
.map::after {
  content: "";
  position: absolute;
  top: 10%;
  left: 0;
  width: 100%;
  height: 100%;
  background: url("../assets/lbx.png") no-repeat center;
  background-size: 60% 70%;
  opacity: 0.4; /* 透明度 50% */
  z-index: -1; /* 确保伪元素在内容下方 */
}
</style>